<script setup lang="ts">
import { h, ref, unref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElButton, ElPopconfirm } from "element-plus";
import QrcodeVue from "vue-qrcode";

import { ProSelect } from "@/modules/package/form";
import EnumTag from "@/components/common/EnumTag.vue";

import useAduit from "./useAudit";
import useQrcode from "./useQrcode";
import useProTable from "@/hooks/useProTable";
import ApiActivity from "@/api/activity";

import { parseNumber } from "@/utils/tool";
import {
  batchGetSourceUrls,
  dispatchAppTask,
} from "@/components/task/tastEvent";
import {
  EnumActivityAuditStatus,
  EnumActivityDepositStatus,
} from "@/utils/enum";

const singleUrl = import.meta.env.VITE_APP_SINGLE || "";

const router = useRouter();
const { query } = useRoute();

const refTable = ref();

const { toAduit } = useAduit(() => refTable.value?.refresh());
const { buildQrcode } = useQrcode(() => refTable.value?.refresh());

const tableColumns = [
  { label: "序号", type: "index", minWidth: 70 },
  { label: "品牌名", prop: "merchant_title", minWidth: 160 },
  { label: "已选展位", prop: "stand_title", minWidth: 100 },
  // { label: "商户类别", prop: "stand_id", width: 160 },
  // { label: "城市区域", prop: "address", width: 170 },
  // { label: "活动名称", prop: "title", minWidth: 160 },
  // { label: "活动状态", prop: "act_status", minWidth: 110 },
  // { label: "活动开始时间", prop: "start_time", width: 120 },
  // { label: "活动开始时间", prop: "end_time", width: 120 },

  {
    label: "报名状态",
    width: 100,
    slot: ({ row }: any) =>
      h(EnumTag, {
        options:
          row.audit_status == 1
            ? EnumActivityDepositStatus
            : EnumActivityAuditStatus,
        value: row.audit_status == 1 ? row.deposit_status : row.audit_status,
      }),
  },
  // { label: "押金状态", slot: "deposit_status", width: 100 },
  // { label: "报名时间", prop: "create_time", minWidth: 150 },
  // { label: "审核时间", prop: "audit_time", minWidth: 150 },
  { label: "商户收款码", slot: "charge_qrcode", Width: 160 },
  { label: "操作", slot: "operate", width: 200, fixed: "right" },
];

const formItems = [
  {
    label: "审核状态",
    children: {
      type: ProSelect,
      field: "audit_status",
      props: {
        clearable: true,
        options: [
          { label: "待审核", value: 0 },
          { label: "待支付", value: 1 },
          { label: "已支付", value: 4 },
          { label: "已退回", value: 8 },
          { label: "已拒绝", value: 2 },
        ],
      },
    },
  },
  {
    label: "展位",
    children: {
      type: ProSelect,
      field: "stand_id",
      props: {
        valueKey: "id",
        labelKey: "stand_title",
        clearable: true,
        fetchUrl: ApiActivity.standList,
        fetchOptions: { defaultSearch: { act_id: Number(query.act_id) } },
        // optionPropRender(item: TStall) {
        //   return {
        //     value: item.id,
        //     label: item.stand_title
        //   };
        // }
      },
    },
  },
];

const fetchOptions = {
  routerQuery: true,
  formatUrlParams({ act_id, audit_status, stand_id }: any = {}) {
    return {
      act_id: parseNumber(act_id),
      stand_id: parseNumber(stand_id),
      audit_status: parseNumber(audit_status),
    };
  },
  foramtFetchParams(data: any) {
    if (data.audit_status > 2 || data.audit_status === 1) {
      // 报名审核通过，
      data = Object.assign({}, data, {
        audit_status: 1,
        // 1 已支付 | 2 已退回
        deposit_status: data.audit_status >> 2,
      });
    }

    return data;
  },
};

const sourceUrlKeys = [
  "business_license",
  "merchant_img",
  "merchant_logo_png",
  "merchant_logo_ai",
  "product_img",
];

const [Protable, { tableApi }] = useProTable({
  fetchOptions,
  fetchUrl: ApiActivity.activityApplyList,
  tableOptions: {
    columns: tableColumns,
  },
  formOptions: {
    formItems,
  },
});

/**
 * 下来本页数据资源
 */
const downloadSource = () => {
  unref(tableApi.list).forEach((item: any) => {
    dispatchAppTask({
      title: `【${item.merchant_title}】资源文件`,
      data: batchGetSourceUrls(item, sourceUrlKeys),
    });
  });
};
</script>

<template>
  <Protable>
    <template #tool-left>
      <ElButton type="primary" @click="downloadSource">下载本页商家资源
      </ElButton>
    </template>

    <template #table-charge_qrcode="{ row }">
      <template v-if="![0, 2].includes(row.deposit_status)">
        <QrcodeVue
                   v-if="row.am_key"
                   :value="singleUrl + '/#/pages/merchantpay/index?key=' + row.am_key"
                   :color="{ dark: '#000000', light: false }"
                   type="image/png"
                   :size="120" />

        <ElPopconfirm  v-else
                      title="生成收款码"
                      confirm-button-text="生成"
                      cancel-button-text="取消"
                      cancel-button-type="danger"
                      @confirm="buildQrcode(row)">
          <template #reference>
            <ElButton link type="danger">生成收款码</ElButton>
          </template>
        </ElPopconfirm>
      </template>
    </template>

    <template #table-operate="{ row }">
      <ElButton
                link
                type="primary"
                @click="router.push(`/activity/enroll/detail/${row.id}`)">详情</ElButton>

      <ElButton
                link
                type="warning"
                @click="router.push(`/activity/enroll/modify/${row.id}`)">修改</ElButton>

      <ElPopconfirm
                    v-if="row.audit_status == 0"
                    title="审核"
                    confirm-button-text="通过"
                    cancel-button-text="不通过"
                    cancel-button-type="danger"
                    @confirm="toAduit(row, 1)"
                    @cancel="toAduit(row, 2)">
        <template #reference>
          <ElButton link type="danger">审核</ElButton>
        </template>
      </ElPopconfirm>
    </template>
  </Protable>
</template>
